/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/
 */

package com.beem.project.beem.providers;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * Provider to store messages send/receive.
 * @author marseille
 */
public class MessageProvider extends ContentProvider {

	private static final String TAG = "MessageProvider";
	private static final String DATABASE_NAME = "messages.db";
	private static final int DATABASE_VERSION = 1;

	private static final int ACCOUNTS_TABLE = 1;
	private static final int ACCOUNTS_TABLE_ID = 2;
	private static final int CONTACTS_TABLE = 3;
	private static final int CONTACTS_TABLE_ID = 4;
	private static final int CONTACTS_TABLE_ACCOUNT_ID = 5;
	private static final int MESSAGES_TABLE = 6;
	private static final int MESSAGES_TABLE_ID = 7;

	private static final String ACCOUNTS_TABLE_NAME = "accounts";
	private static final String ACCOUNTS_TABLE_NAME_ID = "accounts/#";
	private static final String CONTACTS_TABLE_NAME="contacts";
	private static final String CONTACTS_TABLE_NAME_ID = "contacts/#";
	private static final String CONTACTS_TABLE_NAME_ACCOUNT_ID = "contacts/#";
	private static final String MESSAGES_TABLE_NAME = "messages";
	private static final String MESSAGES_TABLE_NAME_ID = "messages/#";

	private static final UriMatcher sUriMatcher;

	public static final String AUTHORITY = "com.beem.project.beem.providers.messageprovider";

	private DatabaseHelper mDbHelper;
	private static final GetTableAndWhereOutParameter sGetTableAndWhereParam = new GetTableAndWhereOutParameter();
	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, ACCOUNTS_TABLE_NAME, ACCOUNTS_TABLE);
		sUriMatcher.addURI(AUTHORITY, ACCOUNTS_TABLE_NAME_ID, ACCOUNTS_TABLE_ID);
		sUriMatcher.addURI(AUTHORITY, CONTACTS_TABLE_NAME, CONTACTS_TABLE);
		sUriMatcher.addURI(AUTHORITY, CONTACTS_TABLE_NAME_ID, CONTACTS_TABLE_ID);
		sUriMatcher.addURI(AUTHORITY, CONTACTS_TABLE_NAME_ACCOUNT_ID, CONTACTS_TABLE_ACCOUNT_ID);
		sUriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME, MESSAGES_TABLE);
		sUriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME_ID, MESSAGES_TABLE_ID);
	}


	/**
	 * Constructor.
	 */
	 public MessageProvider() {
		 Log.i(TAG, "Constructeur MessageProvider");
	 }

	 @Override
	 public boolean onCreate() {
		 Log.i(TAG, "On Create MessageProvider");
		 mDbHelper = new DatabaseHelper(getContext());
		 return true;
	 }

	 @Override
	 public Uri insert(Uri uri, ContentValues initialValues) {
		 Uri newUri = insertInternal(uri, initialValues);
		 if (newUri != null) {
			 getContext().getContentResolver().notifyChange(uri, null);
		 }
		 return newUri;
	 }

	 @Override
	 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

		 int match = sUriMatcher.match(uri);
		 String groupBy=null;
		 String having=null;
		 String limit = uri.getQueryParameter("limit");
		 getTableAndWhere(uri, match, selection, sGetTableAndWhereParam);
		 SQLiteDatabase db = mDbHelper.getReadableDatabase();
		 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		 Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder, limit);
		 c.setNotificationUri(getContext().getContentResolver(), uri);
		 return c;
	 }

	 @Override
	 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		 int count;
		 SQLiteDatabase db = mDbHelper.getWritableDatabase();
		 int match=sUriMatcher.match(uri);
		 getTableAndWhere(uri, match, selection, sGetTableAndWhereParam);
		 count = db.update(sGetTableAndWhereParam.table, values, sGetTableAndWhereParam.where, selectionArgs);
		 if (count > 0 && !db.inTransaction()) 
			 getContext().getContentResolver().notifyChange(uri, null);
		 return count;
	 }

	 @Override
	 public int delete(Uri uri, String selection, String[] selectionArgs) {
		 int count;
		 int match = sUriMatcher.match(uri);
		 SQLiteDatabase db = mDbHelper.getWritableDatabase();
		 getTableAndWhere(uri, match, selection, sGetTableAndWhereParam);
		 count = db.delete(sGetTableAndWhereParam.table, sGetTableAndWhereParam.where, selectionArgs);
		 if(count>0&&!db.inTransaction())
			 getContext().getContentResolver().notifyChange(uri, null);
		 return count;
	 }

	 @Override
	 public String getType(Uri uri) {
		 switch (sUriMatcher.match(uri)) {
		 case MESSAGES_TABLE:
			 return Messages.CONTENT_TYPE;
		 case MESSAGES_TABLE_ID:
			 return Messages.CONTENT_ITEM_TYPE;
		 case CONTACTS_TABLE:
			 return Contacts.CONTENT_TYPE;
		 case CONTACTS_TABLE_ACCOUNT_ID:
			 return Contacts.CONTENT_TYPE;
		 case CONTACTS_TABLE_ID:
			 return Accounts.CONTENT_ITEM_TYPE;
		 case ACCOUNTS_TABLE:
			 return Accounts.CONTENT_TYPE;
		 case ACCOUNTS_TABLE_ID:
			 return Accounts.CONTENT_ITEM_TYPE;
		 default:
			 throw new IllegalArgumentException("Unknown URI " + uri);
		 }
	 }
	 private Uri insertInternal(Uri uri, ContentValues initialValues){
		 long rowId;
		 Uri newUri = null;;
		 SQLiteDatabase db=mDbHelper.getWritableDatabase();

		 switch(sUriMatcher.match(uri)){
		 case MESSAGES_TABLE:
		 case MESSAGES_TABLE_ID:
			 rowId = db.insert(MESSAGES_TABLE_NAME, Messages.BODY, initialValues);
			 break;
		 case CONTACTS_TABLE_ACCOUNT_ID:
			 int contactAccountId = Integer.parseInt(uri.getPathSegments().get(1));
			 ContentValues values = new ContentValues(initialValues);
			 values.put(Contacts.CONTACTS_ACCOUNT_ID, contactAccountId);
			 rowId = db.insert(CONTACTS_TABLE_NAME, Contacts.CONTACTS_DISPLAY_NAME, values);
			 break;
		 case ACCOUNTS_TABLE:
		 case ACCOUNTS_TABLE_ID:
			 rowId = db.insert(MESSAGES_TABLE_NAME, Accounts.ACCOUNT_SHARED_PREFS, initialValues);
			 break;
		 default:
			 throw new UnsupportedOperationException("Invalid URI " + uri);
		 }
		 if (rowId == -1) 
			 throw new SQLException("Failed to insert row into " + uri);
		 newUri = ContentUris.withAppendedId(uri, rowId);
		 return newUri;
	 }
	 private void getTableAndWhere(Uri uri,int match,String userWhere,GetTableAndWhereOutParameter out){
		 String where=null;
		 switch(match){

		 case MESSAGES_TABLE:
			 out.table = MESSAGES_TABLE_NAME;
			 break;
		 case MESSAGES_TABLE_ID:
			 out.table = MESSAGES_TABLE_NAME;
			 out.where = "_id = "+uri.getPathSegments().get(1);
			 break;

		 case CONTACTS_TABLE:
			 out.table = CONTACTS_TABLE_NAME;
			 break;
		 case CONTACTS_TABLE_ACCOUNT_ID:
			 out.table = CONTACTS_TABLE_NAME;
			 where = "_account_id=" + uri.getPathSegments().get(1);
			 break;
		 case CONTACTS_TABLE_ID:
			 out.table = CONTACTS_TABLE_NAME;
			 where = "_id=" + uri.getPathSegments().get(1);
			 break;

		 case ACCOUNTS_TABLE:
			 out.table = ACCOUNTS_TABLE_NAME;
			 break;
		 case ACCOUNTS_TABLE_ID:
			 out.table = CONTACTS_TABLE_NAME;
			 where = "_id=" + uri.getPathSegments().get(1);
			 break;

		 default:
			 throw new UnsupportedOperationException(
					 "Unknown or unsupported URL: " + uri.toString());
		 }
		 // Add in the user requested WHERE clause, if needed
		 if (!TextUtils.isEmpty(userWhere)) {
			 if (!TextUtils.isEmpty(where)) {
				 out.where = where + " AND (" + userWhere + ")";
			 } else {
				 out.where = userWhere;
			 }
		 } else {
			 out.where = where;
		 }
	 }
	 private static final class GetTableAndWhereOutParameter{
		 public String table;
		 public String where;
	 }
	 private class DatabaseHelper extends SQLiteOpenHelper {

		 DatabaseHelper(Context context) {
			 super(context, DATABASE_NAME, null, DATABASE_VERSION);
			 Log.e(TAG, "ConStructeur");
		 }

		 @Override
		 public void onCreate(SQLiteDatabase db) {
			 Log.e(TAG, "onCreate");

			 String createAccountTable = "CREATE TABLE " + ACCOUNTS_TABLE_NAME + " (";
			 createAccountTable += Accounts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
			 createAccountTable += Accounts.ACCOUNT_SHARED_PREFS + " VARCHAR(255),";
			 createAccountTable += Accounts.ACCOUNT_ORDERBY + " INTEGER DEFAULT 0,";
			 createAccountTable += ");";

			 String createContactTable = "CREATE TABLE " + CONTACTS_TABLE_NAME + " (";
			 createContactTable += Contacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
			 createContactTable += Contacts.CONTACTS_ACCOUNT_NAME + " VARCHAR(255),";
			 createContactTable += "FOREIGN KEY("+Contacts.CONTACTS_ACCOUNT_ID+") REFERENCES "+ACCOUNTS_TABLE_NAME+"("+Accounts._ID+")"
					 +");";

			 String createMessageTable = "CREATE TABLE " + MESSAGES_TABLE_NAME + " (";
			 createMessageTable += Messages._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
			 createMessageTable += Messages.FROM + " VARCHAR(255),";
			 createMessageTable += Messages.MESSAGE_ID + " VARCHAR(255),";
			 createMessageTable += Messages.TO + " VARCHAR(255),";
			 createMessageTable += Messages.TYPE + " VARCHAR(255),";
			 createMessageTable += Messages.SUBJECT + " VARCHAR(255),";
			 createMessageTable += Messages.BODY + " LONGTEXT,";
			 createMessageTable += Messages.THREAD + " VARCHAR(255),";
			 createMessageTable += Messages.EXTRAS + " VARCHAR(255),";
			 createMessageTable += Messages.IS_RECEIVE + " BOOLEAN,";
			 createMessageTable += Messages.DATE_RECEIVE + " DATE,";
			 createMessageTable += Messages.DATE_READ + " DATE";
			 createMessageTable += ");";

			 try {
				 db.execSQL(createAccountTable);
				 db.execSQL(createContactTable);
				 db.execSQL(createMessageTable);
			 } catch (SQLException e) {
				 Log.e(TAG, "CREATE DB PROBLEM", e);
			 }
		 }

		 @Override
		 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			 Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
					 + ", which will destroy all old data");
			 db.execSQL("DROP TABLE IF EXISTS " + MESSAGES_TABLE_NAME);
			 onCreate(db);
		 }
	 }

}
